<?php
/**
 * 基础物料模型层
 *
 * @author kamisama.xia@gmail.com
 * @version 0.1
 */

class material_mdl_basic_material extends dbeav_model{

    var $defaultOrder = array('bm_id',' DESC');

    /**
     * 基础物料列表项扩展字段
     */
    function extra_cols(){
        return array(
            'column_cost' => array('label'=>'成本价','width'=>'75','func_suffix'=>'cost'),
            'column_retail_price' => array('label'=>'售价','width'=>'75','func_suffix'=>'retail_price'),
            'column_weight' => array('label'=>'重量','width'=>'75','func_suffix'=>'weight'),
            'column_unit' => array('label'=>'包装单位','width'=>'75','func_suffix'=>'unit'),
            'column_barcode' => array('label'=>'条形码','width'=>'125','func_suffix'=>'barcode'),
            'column_specifications' => array('label'=>'物料规格','width'=>'120','func_suffix'=>'specifications'),
            'column_brand' => array('label'=>'物料品牌','width'=>'120','func_suffix'=>'brand'),
        );
    }

    /**
     * 条码扩展字段格式化
     */
    function extra_barcode($rows){
        return kernel::single('material_extracolumn_basicmaterial_barcode')->process($rows);
    }

    /**
     * 成本扩展字段格式化
     */
    function extra_cost($rows){
        return kernel::single('material_extracolumn_basicmaterial_cost')->process($rows);
    }

    /**
     * 售价扩展字段格式化
     */
    function extra_retail_price($rows){
        return kernel::single('material_extracolumn_basicmaterial_retailprice')->process($rows);
    }

    /**
     * 重量扩展字段格式化
     */
    function extra_weight($rows){
        return kernel::single('material_extracolumn_basicmaterial_weight')->process($rows);
    }

    /**
     * 包装单位扩展字段格式化
     */
    function extra_unit($rows){
        return kernel::single('material_extracolumn_basicmaterial_unit')->process($rows);
    }

    /**
     * 物料规格字段格式化
     */
    function extra_specifications($rows){
        return kernel::single('material_extracolumn_basicmaterial_specifications')->process($rows);
    }

    /**
     * 物料品牌字段格式化
     */
    function extra_brand($rows){
        return kernel::single('material_extracolumn_basicmaterial_brand')->process($rows);
    }

    /**
     * 物料类型字段格式化
     * @param string $row 物料类型字段
     * @return string
     */
    function modifier_type($row){
        if($row == '1'){
            return '普通';
        }elseif($row == '2'){
            return '组合';
        }
    }

    /**
     * 物料是否可见字段格式化
     * @param string $row 物料是否可见字段
     * @return string
     */
    function modifier_visibled($row){
        if($row == '1'){
            return '可售';
        }elseif($row == '2'){
            return '停售';
        }
    }

    /**
     * 导入模板的标题
     *
     * @param Null
     * @return Array
     */
    function exportTemplate($filter){
        foreach ($this->io_title($filter) as $v){
            $title[] = kernel::single('base_charset')->utf2local($v);
        }
        return $title;
    }

    /**
     * 导入导出的标题
     *
     * @param Null
     * @return Array
     */
    function io_title( $filter, $ioType='csv' ){
        switch( $filter ){
            case 'basicM':
                $this->oSchema['csv'][$filter] = array(
                    '*:基础物料名称' => 'material_name',
                    '*:基础物料编码' => 'material_bn',
                    '*:基础物料属性' => 'material_type',
                    '*:条码' => 'barcode',
                    '*:是否可售' => 'visibled',
                    '*:计量单位' => 'unit',
                    '*:销售价' => 'retail_price',
                    '*:成本价' => 'cost',
                    '*:重量' => 'weight',
                    '*:组合类物料信息' => 'bind_info',
                    '*:是否启用保质期监控' => 'use_expire',
                    '*:预警天数配置' => 'warn_day',
                    '*:自动退出库存天数配置' => 'quit_day',
                    '*:基础物料类型' => 'specifications',
                    '*:规格' => 'cat_id',
                    '*:品牌' => 'brand_id',
                );
                break;
        }
        $this->ioTitle[$ioType][$filter] = array_keys( $this->oSchema[$ioType][$filter] );
        return $this->ioTitle[$ioType][$filter];
    }


    /**
     * 准备导入的参数定义
     *
     * @param Null
     * @return Null
     */
    function prepared_import_csv(){
        $this->ioObj->cacheTime = time();
    }

    /**
     * 准备导入的数据主体内容部分检查和处理
     *
     * @param Array $data
     * @param Boolean $mark
     * @param String $tmpl
     * @param String $msg
     * @return Null
     */
    function prepared_import_csv_obj($data,$mark,$tmpl,&$msg = ''){
        return null;
    }

    /**
     * 准备导入的数据明细内容部分检查和处理
     *
     * @param Array $row
     * @param String $title
     * @param String $tmpl
     * @param Boolean $mark
     * @param Boolean $newObjFlag
     * @param String $msg
     * @return Null
     */
    function prepared_import_csv_row($row,$title,&$tmpl,&$mark,&$newObjFlag,&$msg){

        if (empty($row)){
            return true;
        }
        $mark = false;

        if( substr($row[0],0,1) == '*' ){
            $titleRs =  array_flip($row);
            $mark = 'title';

            return $titleRs;
        }else{
            $re = base_kvstore::instance('basic_material')->fetch('basic-'.$this->ioObj->cacheTime,$fileData);

            if( !$re ) $fileData = array();

            if(!$row[0]){
                $msg['error'] = "基础物料名称必须填写";
                return false;
            }

            if(!$row[1]){
                $msg['error'] = "基础物料编码必须填写";
                return false;
            }

            if(!$row[2]){
                $msg['error'] = "基础物料属性必须填写";
                return false;
            }

            if(!$row[3]){
                $msg['error'] = "条码必须填写";
                return false;
            }

            if(!$row[4]){
                $msg['error'] = "是否可售必须填写";
                return false;
            }

            if(isset($this->basicm_nums)){
                $this->basicm_nums ++;
                if($this->basicm_nums > 5000){
                    $msg['error'] = "导入的数量量过大，请减少到5000个以下！";
                    return false;
                }
            }else{
                $this->basicm_nums = 0;
            }

            //基础物料类型判断
            if(!empty($row[13])){
                $goods_type_obj = app::get('ome')->model('goods_type');
                $goods_types = $goods_type_obj->getList('type_id,name', array());
                $flag = false;
                foreach($goods_types as $k => $v){
                    if($v['name'] == $row[13]){
                        $flag = $v['type_id'];
                    }
                }
                if($flag){
                    $row[13] = $flag;
                } else {
                    $msg['error'] = "基础物料类型：".$row[13]." 不存在";
                    return false;
                }
            }


            // 基础物料品牌判断
            if(!empty($row[15])){
                $brand_id = false;
                $brand_obj = app::get('ome')->model('brand');
                $all_brands = $brand_obj->getList('brand_id, brand_name', array());
                foreach($all_brands as $kk => $vv){
                    if($vv['brand_name'] == $row[15]){
                        $brand_id = $vv['brand_id'];
                    }
                }
                if($brand_id){
                    $row[15] = $brand_id;
                } else {
                    $msg['error'] = "基础物料品牌：".$row[15]." 不存在";
                    return false;
                }
            }


            //判断基础物料是否存在
            $basicMaterialObj = app::get('material')->model('basic_material');
            $basicMaterialInfo = $basicMaterialObj->getList('bm_id',array('material_bn'=>$row[1]));
            if($basicMaterialInfo){
                $msg['error'] = "基础物料编码已存在：".$row[1];
                return false;
            }

            //判断条码是否已经存在占用
            $barcodeObj = app::get('material')->model('barcode');
            $barcodeInfo = $barcodeObj->getList('bm_id',array('code'=>$row[3]));
            if($barcodeInfo){
                $msg['error'] = "条码存在已被占用：".$row[3];
                return false;
            }

            if($row[2] =="普通"){
                $row[2] = 1;
            }elseif($row[2] =="组合"){
                $row[2] = 2;
            }else{
                $msg['error'] = "基础物料属性填写的内容错误：".$row[2]."，请填写普通或组合";
                return false;
            }

            //如果是组合类型并且定义了绑定明细的话，重组下数据
            if($row[2] == 2){
                if(isset($row[9]) && !empty($row[9])){
                    $tmp_basicMInfos = explode('|',$row[9]);
                    foreach($tmp_basicMInfos as $tmp_basicMInfo){
                        $tmp_bnInfo = explode(':',$tmp_basicMInfo);
                        $tmp_binds[$tmp_bnInfo[0]] = $tmp_bnInfo[1];
                    }
                    unset($row[9]);

                    $row[9] = $tmp_binds;
                    foreach($row[9] as $bn => $val){
                        $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$bn), 0, 1);
                        if(!$basicInfo){
                            $msg['error'] = "找不到关联的基础物料：".$bn;
                            return false;
                        }else{
                            $tmp_at[$basicInfo[0]['bm_id']] = $val;
                            $basicM_bns[$bn] = $basicInfo[0]['bm_id'];
                        }
                    }
                    unset($row[9]);
                    $row[9] = $tmp_at;
                }else{
                    $msg['error'] = "组合物料请至少设置一个物料明细内容：".$row[1];
                    return false;
                }
            }

            if($row[4] =="在售"){
                $row[4] = 1;
            }elseif($row[4] =="停售"){
                $row[4] = 2;
            }else{
                $msg['error'] = "是否可售填写的内容错误：".$row[4]."，请填写在售或停售";
                return false;
            }

            if($row[10] =="开启"){
                $row[10] = 1;
            }elseif($row[10] =="关闭"){
                $row[10] = 2;
            }else{
                $msg['error'] = "是否启用保质期监控的内容错误：".$row[10]."，请填写开启或关闭";
                return false;
            }

            $fileData['basicm']['contents'][] = $row;
            base_kvstore::instance('basic_material')->store('basic-'.$this->ioObj->cacheTime,$fileData);

        }
        return null;
    }

    /**
     * 完成基础物料的导入
     *
     * @param Null
     * @return Null
     */
    function finish_import_csv(){
        base_kvstore::instance('basic_material')->fetch('basic-'.$this->ioObj->cacheTime,$data);
        base_kvstore::instance('basic_material')->store('basic-'.$this->ioObj->cacheTime,'');

        $oQueue = app::get('base')->model('queue');
        $aP = $data;
        $pSdf = array();

        $count = 0;
        $limit = 50;
        $page = 0;
        $orderSdfs = array();

        foreach ($aP['basicm']['contents'] as $k => $aPi){
            if($count < $limit){
                $count ++;
            }else{
                $count = 0;
                $page ++;
            }
            $pSdf[$page][] = $aPi;
        }

        foreach($pSdf as $v){
            $queueData = array(
                'queue_title'=>'基础物料导入',
                'start_time'=>time(),
                'params'=>array(
                    'sdfdata'=>$v,
                    'app' => 'material',
                    'mdl' => 'basic_material'
                ),
                'worker'=>'material_basic_material_to_import.run',
            );
            $oQueue->save($queueData);
        }
        $oQueue->flush();
        return null;
    }
}
